package com.example.victory.service.task;

import com.example.victory.entity.companyEntity.AccountIncompleteEntity;
import com.example.victory.entity.companyEntity.LossWarningEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.service.InnerService;
import com.cgws.fintech.sdk.api.inner.security.model.ApiResponseListAccountReal;
import com.cgws.fintech.sdk.common.cache.RedisService;
import com.cgws.fintech.sdk.common.lock.Synchronized;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CrmTask {
    @Autowired
    private InnerService innerService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RedisService redisService;

    private static final String REDIS_PREFIX = "inner-business-customer";

    @Synchronized(namespace = "inner-business-customer:accountIncomplete-lossWarning", expireSecond = 600)
    @Scheduled(cron = "${app.lossWarning.accountIncomplete.sync:0 0 6 * * ?}")
    public void getCrmDataJob() {
        List<String> accountRealList = getAccountRealList();
        if (accountRealList == null) return;
        List<List<String>> groupList = generateGroup(accountRealList);

        // 获取往前第30个交易日的日期
        Integer nowDate = Integer.valueOf(DateHelper.getDateYYYYMMDD(new Date()));
        Integer beforeTradeDay = customerMapper.getTradingDay(nowDate,30);

        // 获取昨天往前第30个交易日的日期，用于删除过时数据
        Date yesterday = DateHelper.increment(new Date(), -1, Calendar.DATE);
        Integer nowDate_yesterday = Integer.valueOf(DateHelper.getDateYYYYMMDD(yesterday));
        Integer beforeTradeDay_yesterday = customerMapper.getTradingDay(nowDate_yesterday,30);
        // 定时任务只缓存第一页的数据
        Integer start = 0;
        Integer end = 20;
        log.info("离线获取账户不完整&流失预警开始...{}", nowDate);
        ExecutorService executorService= Executors.newFixedThreadPool(groupList.size());
        groupList.forEach(strList -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    strList.forEach(crmId -> {
                        long startTime = System.currentTimeMillis();
                        // 账户不完整-三方存管异常
                        List<AccountIncompleteEntity> threeWayPipeList = customerMapper.getThreeWayPipe(crmId, start, end);
                        redisService.getRedisTemplate().opsForValue().set(REDIS_PREFIX + "::accountIncomplete:threeWayPipe:" + crmId + ":" + start + ":" + end, threeWayPipeList, 20, TimeUnit.HOURS);
                        // 账户不完整-股东卡异常
                        List<AccountIncompleteEntity> shareholdersCardList = customerMapper.getShareholdersCard(crmId, start, end);
                        redisService.getRedisTemplate().opsForValue().set(REDIS_PREFIX + "::accountIncomplete:shareholdersCard:" + crmId + ":" + start + ":" + end, shareholdersCardList, 20, TimeUnit.HOURS);
                        long accountIncompleteEndTime = System.currentTimeMillis();
                        log.info("同步{}账户不完整数据完成,耗时={}ms",crmId, accountIncompleteEndTime - startTime);

                        // 流失预警-大比例转出
                        List<LossWarningEntity> bigRollOutList = customerMapper.getCustLossWarnBigRollOutPage(crmId, start, end, beforeTradeDay, nowDate);
                        redisService.getRedisTemplate().opsForValue().set(REDIS_PREFIX + "::lossWarning:bigRollOut:" + crmId + ":" + start + ":" + end + ":" + beforeTradeDay + ":" + nowDate, bigRollOutList, 72, TimeUnit.HOURS);
                        redisService.getRedisTemplate().delete(REDIS_PREFIX + "::lossWarning:bigRollOut:" + crmId + ":" + start + ":" + end + ":" + beforeTradeDay_yesterday + ":" + nowDate_yesterday);
                        // 流失预警-撤指定
                        List<LossWarningEntity> turnToHostList = customerMapper.getCustLossWarnturnToHostPage(crmId, start, end, beforeTradeDay, nowDate);
                        redisService.getRedisTemplate().opsForValue().set(REDIS_PREFIX + "::lossWarning:turnToHost:" + crmId + ":" + start + ":" + end + ":" + beforeTradeDay + ":" + nowDate, turnToHostList, 72, TimeUnit.HOURS);
                        redisService.getRedisTemplate().delete(REDIS_PREFIX + "::lossWarning:turnToHost:" + crmId + ":" + start + ":" + end + ":" + beforeTradeDay_yesterday + ":" + nowDate_yesterday);
                        long lossWarningEndTime = System.currentTimeMillis();
                        log.info("同步{}流失预警数据完成,耗时={}ms",crmId, lossWarningEndTime - accountIncompleteEndTime);
                    });
                }
            });
        });
        try {
            executorService.shutdown();
            executorService.awaitTermination(90,TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            log.error("线程池出错,e={}",e);
        }
        log.info("离线获取账户不完整&流失预警结束...{}", nowDate);
    }

    /**
     * 获取crm系统里的ryid列表
     * @return  ryid列表
     */
    private List<String> getAccountRealList() {
        ResponseEntity<ApiResponseListAccountReal> response = innerService.listAccountReal();
        if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null || response.getBody().getData() == null) {
            return null;
        }
        List<String> accountRealList = response.getBody().getData().getAccountRealList();
        if (accountRealList == null || accountRealList.size() == 0) {
            return null;
        }
        return accountRealList;
    }

    /**
     * 给list分组
     * @param list  需要被分组的list
     * @return  分组后的list
     */
    private List<List<String>> generateGroup(List<String> list) {
        int groupSize = 200;
        int size = list.size();
        int groupCount = (int) Math.ceil(size / (double)groupSize);

        List<List<String>> groupList = Lists.newArrayList();
        for (int i = 0; i < groupCount; i++) {
            List<String> stringList = Lists.newArrayList();
            for (int j = groupSize * i; j < groupSize * (i+1); j++) {
                if (j < size) {
                    stringList.add(list.get(j));
                }
            }
            groupList.add(stringList);
        }
        return groupList;
    }
}
